<template>
	<view class="shoppingCart">
		<view v-if="$store.getters.token || userInfo.uid">

			<view class="nav acea-row row-between-wrapper a">
				<view>
					<view v-if="validList.length > 0" class="administrate acea-row row-center-wrapper" @click="setting">{{ '批量设置' }}</view>
				</view>
				
				<view v-if="validList.length > 0" class="administrate acea-row row-center-wrapper" @click="manage">{{ footerswitch ? '取消' : '删除管理' }}</view>
				
			
				
			</view>
			<view v-if="validList.length > 0 || cartList.invalid.length > 0">
				<view class="list">
					<!--商户名称start-->
					<view v-for="(validList, key) in validMap" :key="key">
						<view class=" shop-tip" style="padding: 0.5rem">
							<view class="select-btn">
								<view class="checkbox-wrapper">
									<!-- 	<checkbox-group >
										  <label class="well-check">
											<checkbox color="#eb3729"  ></checkbox>
										  </label>
										</checkbox-group> -->
								</view>
							</view>
							<!-- <view class="shopimg"><image src="http://mall-image.hxyrfwpt.com/static/shop-ico.png"></image></view> -->
							<!-- <view class="shopname">{{ key }}</view> -->
							<!-- <view class="iconfont icon-jiantou shop-arrow"></view> -->
						</view>

						<view class="item acea-row row-between-wrapper" v-for="(item, cartListValidIndex) in validList" :key="cartListValidIndex">
							<view class="select-btn">
								<view class="checkbox-wrapper">
									<checkbox-group @change="switchSelect(item, cartListValidIndex)">
										<label class="well-check"><checkbox color="#eb3729" value :checked="item.checked"></checkbox></label>
									</checkbox-group>
								</view>
							</view>
							<view class="picTxt acea-row row-between-wrapper">
								<view class="pictrue" @click="goGoodsCon(item)">
									<image :src="item.productInfo.attrInfo.image" v-if="item.productInfo.attrInfo" />
									<image :src="item.productInfo.image" v-else />
								</view>
								<view class="text">
									<view class="line1">{{ item.productInfo.storeName }}</view>
									<view class="infor line1" v-if="item.productInfo.attrInfo">属性：{{ item.productInfo.attrInfo.sku }}</view>
									<!-- <view class="money">{{ item.truePrice }}豆</view> -->
								</view>
								<!-- <view class="carnum acea-row row-center-wrapper">
									<view class="reduce" :class="validList[cartListValidIndex].cartNum <= 1 ? 'on' : ''" @click.prevent="reduce(cartListValidIndex)">-</view>
									<view class="num">{{ item.cartNum }}</view>
									<view
										class="plus"
										v-if="validList[cartListValidIndex].attrInfo"
										:class="validList[cartListValidIndex].cartNum >= validList[cartListValidIndex].attrInfo.stock ? 'on' : ''"
										@click.prevent="plus(cartListValidIndex)"
									>
										+
									</view>
									<view
										class="plus"
										v-else
										:class="validList[cartListValidIndex].cartNum >= validList[cartListValidIndex].stock ? 'on' : ''"
										@click.prevent="plus(cartListValidIndex)"
									>
										+
									</view>
								</view> -->
							</view>
						</view>
					</view>

					<!--商户名称end-->
				</view>
	
	
			</view>
			<!--购物车暂无商品-->
			<view class="noCart" v-if="cartList.valid.length === 0 && cartList.invalid.length === 0">
				<view class="pictrue"><image src="http://mall-image.hxyrfwpt.com/static/images/noCart.png" /></view>
				<!-- <Recommend class="tuijian"></Recommend> -->
			</view>
			<!--  <view style="height:210rpx"></view> -->
			<view :class="{ 'footer acea-row row-between-wrapper': true, 'footer-h5': true }" v-if="cartList.valid.length > 0">
				<view>
					<view class="select-btn">
						<view class="checkbox-wrapper">
							<!-- <label class="well-check">
              <input
                type="checkbox"
                name
                value
                :checked="isAllSelect && cartCount > 0"
                @click="allChecked"
              />
              <i class="icon"></i>
              <text class="checkAll">全选 ({{ cartCount }})</text>
              </label>-->

							<checkbox-group @change="allChecked">
								<label class="well-check">
									<checkbox color="#eb3729" value="allSelect" :checked="isAllSelect && cartCount > 0"></checkbox>
									<text class="checkAll">全选 ({{ cartCount }})</text>
								</label>
							</checkbox-group>
						</view>
					</view>
				</view>
				<view class="money acea-row row-middle" v-if="footerswitch === false">
					<text class="font-color-red" style="font-weight: 600;">￥{{ countmoney }}</text>
					<view class="placeOrder" @click="placeOrder">结算</view>
					<!--          <view class="placeOrder bg-color-red" @click="placeOrder(1)" style="width: 90px;border-radius:25px 0 0 25px;background-color:#fea10f !important;margin-left:0px">赠送他人</view>
		      <view class="placeOrder bg-color-red" @click="placeOrder(0)" style="width: 90px;border-radius:0 25px 25px 0;margin-left:0px">买给自己</view> -->
				</view>
				<view class="button acea-row row-middle" v-else>
					<!-- <view class="bnt cart-color" @click="collectAll">收藏</view> -->
					<view class="bnt" @click="delgoods">删除</view>
				</view>
				<!-- 
				<uni-fab ref="fab" :pattern="pattern"  horizontal="right" vertical="bottom"
							direction="horizontal"  @fabClick="fabClick" > -->
							<yt-upload
							class="iconipload"
							    ref="ytUpload"
							    childId="upload1"
							    :width="width"
							    :height="height"
							    :option="option"
							    :size="size"
							    :formats="formats"
							    :debug="debug"
							    :instantly="instantly"
							    @uploadEnd="uploadEnd"
							    @change="change">
							        <view class="iconfab" >+</view>
							</yt-upload>
							<!-- </uni-fab> -->
			</view>
			
			<uni-popup ref="popup" background-color="#fff" type="center">
					<view class="popup-content" :class="{ 'popup-height': type === 'left' || type === 'right' }">
						<view class="uni-form-item uni-column">
							<view class="title">纸型</view>
							<view>
								<uni-data-checkbox mode="tag" v-model="set.A" :localdata="A"></uni-data-checkbox>
							</view>
						</view>
						<view class="uni-form-item uni-column">
							<view class="title">颜色</view>
							<view>
								<uni-data-checkbox mode="tag" v-model="set.color" :localdata="color"></uni-data-checkbox>
							</view>
						</view>
					<view class="uni-form-item uni-column">
						<view class="title">单双</view>
						<view>
							<uni-data-checkbox mode="tag" v-model="set.paper" :localdata="paper"></uni-data-checkbox>
						</view>
					</view>

					
					<view class="uni-btn-v">
						<button @click="comfirmSet" class="mini-btn" type="warn" size="mini">确定</button>
	
					</view>
				</view>
			</uni-popup>
		
						
		</view>
	
		<Authorization v-else />
		
	</view>
</template>
<script>
import Recommend from '@/components/Recommend';
import Authorization from '@/pages/authorization/index';
import { VUE_APP_RESOURCES_URL } from '@/config';
import { mapGetters } from 'vuex';

import { getCartList, postCartDel, changeCartNum, getCartCount } from '@/api/store';
import { postCollectAll } from '@/api/user';
import { mul, add } from '@/utils/bc';
import cookie from '@/utils/store/cookie';
import { VUE_APP_API_URL } from '@/config'
const CHECKED_IDS = 'cart_checked';
import store from '@/store'
export default {
	name: 'ShoppingCart',
	components: {
		Recommend,
		Authorization
	},
	props: {},
	data: function() {
		return {
			// 必传宽高且宽高应与slot宽高保持一致
			            width: '180rpx',
			            height: '180rpx',
			 wxFiles: [],
			            // 是否打印日志
			            debug: true,
			
			            // 演示用
			            tabIndex: 0,
			            list:[], 
			 // 文件回显列表
			            files: new Map(),
			// 文件上传大小限制
			            size: 30,
			            // 文件数量限制
			            count: 1,
			// 限制允许上传的格式，空串=不限制，默认为空
			            formats: 'pdf,png,jpg,doc,docx',
			  // 选择文件后是否立即自动上传，true=选择后立即上传
			            instantly: false,
			     // 上传接口参数
			            option: {
			                // 上传服务器地址，需要替换为你的接口地址
			                url: `${VUE_APP_API_URL}/api/upload`, // 该地址非真实路径，需替换为你项目自己的接口地址
			                // 上传附件的key
			                name: 'file',
			                // 根据你接口需求自定义请求头,默认不要写content-type,让浏览器自适配
			                header: {
			                    // 示例参数可删除
			                    'Authorization': 'Bearer ' + store.getters.token
			                },
			                // 根据你接口需求自定义body参数
			                formData: {
			                    // 'orderId': 1000
			                }
			            },
			pattern: {
								color: '#7A7E83',
								backgroundColor: '#fff',
								selectedColor: '#007AFF',
								buttonColor: '#007AFF',
								iconColor: '#fff',
								icon:'plusempty'
							},
			set:{
				A:'',
				color:'',
				paper:''
			},
			A:[
				{text:'A4',value:'A4'},{text:'A3',value:'A3'}
			],
			color:[
				{text:'黑白',value:'bw'},{text:'彩色',value:'all'}
			],
			paper:[
				{text:'单面',value:'bw'},{text:'双面',value:'all'}
			],
			settingswitch:false,
			cartList: {
				invalid: [],
				valid: []
			},
			validMap: [],
			isH5: false,
			bottomValue: 100,
			validList: [],
			isAllSelect: false,
			cartCount: 0,
			countmoney: 0,
			goodsHidden: true,
			footerswitch: false,
			count: 0,
			checkedIds: [],
			loaded: false,
			RESOURCES_URL: VUE_APP_RESOURCES_URL
		};
	},
	computed: mapGetters(['userInfo', 'token']),
	//   watch: {
	//     $yroute(n) {
	//       if (n.name === "ShoppingCart") {
	//         this.carnum();
	//         this.countMoney();
	//         this.getCartList();
	//         this.gainCount();
	//         this.goodsHidden = true;
	//         this.footerswitch = false;
	//       }
	//     },
	//     cartList(list) {
	//       this.validList = list.valid;
	//     }
	//   },
	watch: {
		userInfo(user) {
			if (user.uid) {
				this.carnum();
				this.countMoney();
				this.getCartList();
				this.gainCount();
			}
		},
		token(token) {
			if (this.userInfo.uid) {
				this.carnum();
				this.countMoney();
				this.getCartList();
				this.gainCount();
			}
		},
		cartList(list) {
			this.validList = list.valid;
			// alert(this.validList.length);
		}
	},
	onShow: function() {
		// #ifdef H5
		this.isH5 = true;
		// #endif

		if (this.userInfo.uid) {
			this.carnum();
			this.countMoney();
			this.getCartList();
			this.gainCount();
		}
	},
	methods: {
		uploadEnd(item){
			console.log("上传成功",item)
			 // ---可删除--演示上传完成后取服务端数据
				if (item['responseText']) {
					console.log('演示服务器返回的字符串JSON转Object对象');
					this.files.get(item.name).responseText = JSON.parse(item.responseText);
				}
		},
		change(files){
			console.log(files)
		},

		comfirmSet(){
			
		},
		//悬浮按钮点击
		fabClick(){
			let that = this;
			that.$refs.ytUpload.upload()
		},
		goGoodsCon(item) {
			this.$yrouter.push({
				path: '/pages/shop/GoodsCon/index',
				query: {
					id: item.productId
				}
			});
		},
		getCartList: function() {
			let that = this;
			getCartList().then(res => {
				that.cartList = res.data;
				that.validMap = res.data.validMap;
				let checkedIds = cookie.get(CHECKED_IDS) || [];
				if (!Array.isArray(checkedIds)) checkedIds = [];
				this.cartList.valid.forEach(cart => {
					if (checkedIds.indexOf(cart.id) !== -1) cart.checked = true;
				});
				//map中的购物车ID设置选中状态
				for (let key in that.validMap) {
					that.validMap[key].forEach(cart => {
						if (checkedIds.indexOf(cart.id) !== -1) cart.checked = true;
					});
				}

				if (checkedIds.length) {
					that.checkedIds = checkedIds;
					that.isAllSelect = checkedIds.length === this.cartList.valid.length;
					that.carnum();
					that.countMoney();
				}
				this.loaded = true;
			});
		},
		//删除商品；
		delgoods: function() {
			let that = this,
				id = [],
				valid = [],
				list = that.cartList.valid;
			list.forEach(function(val) {
				if (val.checked === true) {
					id.push(val.id);
				}
			});
			if (id.length === 0) {
				uni.showToast({
					title: '请选择产品',
					icon: 'none',
					duration: 2000
				});
				return;
			}
			postCartDel(id).then(function() {
				list.forEach(function(val, i) {
					if (val.checked === false || val.checked === undefined) valid.push(list[i]);
				});
				that.$set(that.cartList, 'valid', valid);
				that.carnum();
				that.countMoney();
				that.gainCount();
				that.getCartList();
			});
		},
		//设置参数；
		delgoods: function() {
			let that = this,
				id = [],
				valid = [],
				list = that.cartList.valid;
			list.forEach(function(val) {
				if (val.checked === true) {
					id.push(val.id);
				}
			});
			if (id.length === 0) {
				uni.showToast({
					title: '请选择产品',
					icon: 'none',
					duration: 2000
				});
				return;
			}
			// setingCart(id).then(function() {
			// 	that.countMoney();
			// 	that.gainCount();
			// 	that.getCartList();
			// });
		},
		// //获取数量
		gainCount: function() {
			let that = this;
			getCartCount().then(res => {
				that.count = res.data.count;
			});
		},
		//清除失效产品；
		delInvalidGoods: function() {
			let that = this,
				id = [],
				list = that.cartList.invalid;
			list.forEach(function(val) {
				id.push(val.id);
			});
			postCartDel(id).then(function() {
				list.splice(0, list.length);
				that.gainCount();
				that.getCartList();
			});
		},
		//批量收藏;
		collectAll: function() {
			let that = this,
				data = {
					id: [],
					category: ''
				},
				list = that.cartList.valid;
			list.forEach(function(val) {
				if (val.checked === true) {
					data.id.push(val.product_id);
					data.category = val.type;
				}
			});
			if (data.id.length === 0) {
				uni.showToast({
					title: '请选择产品',
					icon: 'none',
					duration: 2000
				});
				return;
			}
			postCollectAll(data).then(function() {
				uni.showToast({
					title: '收藏成功!',
					icon: 'none',
					duration: 2000
				});
			});
		},
		//立即下单；
		placeOrder: function(orderFlag) {
			// sessionStorage.setItem("order_tag",orderFlag);
			let that = this,
				list = that.cartList.valid,
				id = [];
			let merIdCheck = null;
			let merIdFlag = true;
			let shippingTypeFlag = true;
			let shippingType = null; // 配送方式  1=快递 ，2=门店自提 3:全部
			list.forEach(function(val) {
				if (val.checked === true) {
					id.push(val.id);
					// merIdArr.push(val.merId)
					//校验商户ID是否是同一个
					// alert(merIdCheck);
					// console.log(val.productInfo.shippingType,">>>>>>>>>>>>>");
					if (merIdCheck && val.merId != merIdCheck) {
						//alert("不相等");
						merIdFlag = false;
						return;
					} else {
						merIdCheck = val.merId;
					}
					//校验是否是同一配送类型
					if (shippingType && val.productInfo.shippingType && val.productInfo.shippingType != 3 && val.productInfo.shippingType != shippingType) {
						shippingTypeFlag = false;
						return;
					} else {
						shippingType = val.productInfo.shippingType;
					}
				}
			});

			if (id.length === 0) {
				uni.showToast({
					title: '请选择产品',
					icon: 'none',
					duration: 2000
				});
				return;
			}

			if (merIdFlag == false) {
				uni.showToast({
					title: '请选择同一家商品购买',
					icon: 'none',
					duration: 2000
				});
				return;
			}

			if (shippingTypeFlag == false) {
				uni.showToast({
					title: '请选择同一种配送方式!',
					icon: 'none',
					duration: 2000
				});
				return;
			}

			this.$yrouter.push({
				path: '/pages/order/OrderSubmission/index',
				query: {
					id: id.join(',')
				}
			});
		},
		manage: function() {
			let that = this;
			that.footerswitch = !that.footerswitch;
		},
		setting: function() {
			let that = this;
			that.$refs.popup.open()
			
			
		},
		goodsOpen: function() {
			let that = this;
			that.goodsHidden = !that.goodsHidden;
		},

		//加
		plus: function(index) {
			let that = this;
			let list = that.cartList.valid[index];
			list.cartNum++;
			if (list.attrInfo) {
				if (list.cartNum >= list.attrInfo.stock) {
					that.$set(list, 'cart_num', list.attrInfo.stock);
				}
			} else {
				if (list.cartNum >= list.stock) {
					that.$set(list, 'cart_num', list.stock);
				}
			}
			that.carnum();
			that.countMoney();
			that.syncCartNum(list);
		},
		//减
		reduce: function(index) {
			let that = this;
			let list = that.cartList.valid[index];
			if (list.cartNum <= 1) {
				uni.showToast({
					title: '已经是底线啦!',
					icon: 'none',
					duration: 2000
				});
				return;
			}
			list.cartNum--;
			if (list.cartNum < 1) {
				that.$set(list, 'cart_num', 1);
			}
			that.carnum();
			that.countMoney();
			that.syncCartNum(list);
		},
		syncCartNum(cart) {
			if (!cart.sync) {
				changeCartNum(cart.id, Math.max(cart.cartNum, 1) || 1)
					.then(res => {
						this.getCartList();
						this.gainCount();
					})
					.catch(error => {
						this.gainCount();
						uni.showToast({
							title: error.response.data.msg,
							icon: 'none',
							duration: 2000
						});
					});
			}
		},
		//单选
		switchSelect: function(aa, index) {
			let that = this,
				// cart = that.cartList.valid[index],
				// cart = aa,
				i = this.checkedIds.indexOf(aa.id);
			let cart = that.cartList.valid.filter(item => item.id == aa.id)[0];
			cart.checked = !cart.checked;
			// console.log(JSON.stringify(aa),"aa");
			// console.log(JSON.stringify(cart),"cart");
			// alert(cart.id);

			if (i !== -1) this.checkedIds.splice(i, 1);
			if (cart.checked) {
				this.checkedIds.push(cart.id);
			}

			let len = that.cartList.valid.length;
			let selectnum = [];
			for (let i = 0; i < len; i++) {
				if (that.cartList.valid[i].checked === true) {
					selectnum.push(true);
				}
			}
			that.isAllSelect = selectnum.length === len;
			that.$set(that, 'cartList', that.cartList);
			that.$set(that, 'isAllSelect', that.isAllSelect);
			cookie.set(CHECKED_IDS, that.checkedIds);
			that.carnum();
			that.gainCount();
			that.countMoney();
		},
		//全选
		allChecked: function(e) {
			console.log(e);
			let that = this;
			let selectAllStatus = e.mp.detail.value[0] == 'allSelect' ? true : false;
			console.log(selectAllStatus);
			// let selectAllStatus = that.isAllSelect;
			let checkedIds = [];
			// for (let i = 0; i < array.length; i++) {
			//   array[i].checked = selectAllStatus;
			//   checked.push()
			// }
			that.cartList.valid.forEach(cart => {
				cart.checked = selectAllStatus;
				if (selectAllStatus) {
					checkedIds.push(cart.id);
					//把所有map
				}
			});

			for (let key in that.validMap) {
				that.validMap[key].forEach(cart => {
					cart.checked = selectAllStatus;
					if (selectAllStatus) {
						checkedIds.push(cart.id);
					}
				});
			}

			let cartList = {
				...that.cartList
			};
			that.cartList = [];
			that.cartList = cartList;
			console.log(this.cartList);
			this.$set(this, 'cartList', this.cartList);
			this.$set(this, 'isAllSelect', selectAllStatus);
			this.checkedIds = checkedIds;
			cookie.set(CHECKED_IDS, checkedIds);
			that.carnum();
			that.countMoney();
			this.$forceUpdate();
		},
		//数量
		carnum: function() {
			let that = this;
			var carnum = 0;
			var array = that.cartList.valid;
			for (let i = 0; i < array.length; i++) {
				if (array[i].checked === true) {
					carnum += parseInt(array[i].cartNum);
				}
			}
			that.$set(that, 'cartCount', carnum);
		},
		//总共价钱；
		countMoney: function() {
			let that = this;
			let carmoney = 0;
			let array = that.cartList.valid;
			for (let i = 0; i < array.length; i++) {
				if (array[i].checked === true) {
					carmoney = add(carmoney, mul(array[i].cartNum, array[i].truePrice));
				}
			}
			that.countmoney = carmoney;
		}
	}
};
</script>

<style lang="less">
.footer-h5 {
	// bottom: 100rpx !important;
	bottom: var(--window-bottom);
}
.nav {
	background-color: #fff;
	color: #333;
}
.shoppingCart {
	position: relative;
	background-color: #fff;
}
.shoppingCart .nav {
	top: 0rpx;
}
.administrate.acea-row.row-center-wrapper {
	background-color: #fff;
}
.shoppingCart .list .item {
	margin-top: 0rem;
	background-color: #fff;
}
.shoppingCart .list {
	background-color: #fff;
}
.shop-item {
	padding: 0.25 * 100rpx 0.3 * 100rpx;
	background-color: #fff;
}
.shop-item .select-btn {
	margin-right: 5px;
	-webkit-appearance: none;
	appearance: none;
	outline: 0;
	border: 1px solid #d1d1d1;
	background-color: #fff;
	border-radius: 3px;
	width: 22px;
	height: 22px;
	position: relative;
}

/**/
.shop-tip {
	display: flex;
	justify-content: flex-start;
	align-items: center;
	background-color: #fff;
}

.shopimg image {
	width: 16px;
	height: 14.5px;
	margin-left: 7px;
	margin-right: 6px;
}
.shopname {
	font-size: 16px;
	color: #000000;
}
.iconfont.icon-jiantou.shop-arrow {
	font-size: 11px;
	color: #d1d1d1;
	margin-left: 12px;
}
.tuijian {
	background-color: #18d0bf;
}


.uni-px-5 {
	    padding-left: 10px;
	    padding-right: 10px;
	}
	.popup-content{
		    background-color: #fff;
		    padding: 42px;
		    width: 250px;
		    display: grid;
		    justify-content: space-between;
	}
	.iconipload{
		        right: 10px;
		        position: fixed;
		        width: 85px;
		        /* padding: 5px; */
		        height: 88px;
		        bottom: 54px;
	}
	.iconfab{
		    line-height: 80px;
		    position: unset;
		    width: 80px;
		    height: 80px;
		    background-color: #0095ff;
		    color: #fff;
		    border-radius: 100px;
		    box-shadow: 4px 1px 14px 0px black;
		    display: flex;
		    justify-content: center;
			    font-size: 40px;
	}
</style>
